package com.mrxu.monitor.util;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


/**
 * spring bean 工具类
 * @author zzt
 */
@Slf4j
@Component
public class MonitorSpringUtils implements ApplicationContextAware {
	
	/**
	 * spring 上下文
	 */
    private static ApplicationContext applicationContext;
    
    /**
     * 设置spring 上下文
     * @param applicationContext spring 上下文
     * @throws BeansException 对象异常
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (MonitorSpringUtils.applicationContext == null) {
            MonitorSpringUtils.applicationContext = applicationContext;
            log.info("ApplicationContext Initialized.");
        }
    }
    
    /**
     * 获取spring 上下文
     * @return spring 上下文
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    
    /**
     * 获取对象
     * @param clazz class类
     * @param <T> 泛型
     * @return 对象
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
    
    /**
     * 获取对象
     * @param name 对象名
     * @return 对象
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    
    /**
     * 复制对象
     * @param source 源
     * @param target 目标
     */
    public static void copyObject(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }
}
